<template>
  <div>
    <div class="filter">
      <button
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: currentTab === tab.value }"
        @click="changeTab(tab.value)"
      >
        {{ tab.label }} <span v-if="tab.count !== null">{{ tab.count }}</span>
      </button>
      <div class="floating-bar" v-if="isAnySelected">
        <button class="select-all-button" @click="toggleSelectAll" style="margin-right: 15px;">
          {{ allSelectedOnPage ? '取消全选' : '本页全选' }}
        </button>
        <button class="batch-delete-button" @click="batchDeleteExams" style="margin-right: 15px;">批量删除</button>
      </div>
      <button class="create-button" @click="toggleNewExamMenu">新建问卷</button>
    </div>

    <!-- 新建问题菜单 -->
    <div v-if="newExamMenuVisible" class="new-question-menu">
      <span @click="navigateToNewExam">重新组卷</span>
      <span @click="selectExistingExam">选择问卷</span>
    </div>

    <div v-if="newSurveyDialogVisible" class="dialog-overlay" @click.self="newSurveyDialogVisible = false">
      <div @click.stop style="width: 400px;background-color:white;border-radius: 10px;wudth:auto;padding:20px">
        <h3>新建问卷</h3>
        <input 
          v-model="newSurvey.paper_title" 
          placeholder="请输入问卷标题" 
          class="input-field"
        />
        <textarea
          v-model="newSurvey.paper_content"
          placeholder="请输入问卷内容"
          class="input-field"
          rows="5"
        ></textarea>
        <div class="dialog-actions">
          <button @click="newSurveyDialogVisible = false" class="bac-button">取消</button>
          <button @click="createNewSurvey" class="confirm-button">确认创建</button>
        </div>
      </div>
    </div>
    <!-- 问卷列表 -->
    <div
      v-for="exam in paginatedExams"
      :key="exam.exam_id"
      class="exam-card"
      @click="navigateToAnalysis(exam)"
      @mouseenter="exam.showActions = true"
      @mouseleave="exam.showActions = false"
    >
      <!-- 复选框 -->
      <input
        type="checkbox"
        class="exam-checkbox"
        :checked="selectedExams.has(exam.survey_id)"
        @click.stop="toggleSelection(exam.survey_id)"
      />

      <div class="exam-content">
        <div class="exam-header">
          <span class="badge" :class="statusBadgeClass(exam.status)">
            {{ statusLabel(exam.status) }}
          </span>
          <p style="font-weight:bold;">{{ exam.paper_title }}</p>
          <div v-show="exam.showActions" class="exam-actions">
            <button class="edit-button" @click.stop="editSurvey(exam.paper_id)">编辑</button>
            <button class="edit-button" @click.stop="openPublishSurveyDialog(exam.sem_survey_id)">发布</button>
            <button class="edit-button" @click.stop="deleteSingleSurvey(exam.survey_id)">删除</button>
          </div>
        </div>
        <div style="display:flex; font-size: 12px; color: gray;">
          <p style="margin-right: 10px;">结束时间: {{ exam.end_time }}</p>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <PagiNation :currentPage="currentPage" :totalPages="totalPages" @page-change="handlePageChange" />
    <!-- 发布问卷设置模态框 -->
    <div v-if="publishSurveyDialogVisible" class="dialog-overlay" @click.self="publishSurveyDialogVisible = false">
      <div @click.stop style="width: 400px;background-color:white;border-radius: 10px;wudth:auto;padding:20px">
        <h3>发布设置</h3>
        <label for="end-time">截止时间:</label>
        <input
          v-model="endTime"
          type="datetime-local"
          class="input-field"
          id="end-time"
        />
        <div class="dialog-actions">
          <button @click="publishSurveyDialogVisible = false" class="bac-button">取消</button>
          <button @click="publishSurvey" class="confirm-button">确认发布</button>
        </div>
      </div>
    </div>

    <!-- 问卷库模态框 -->
    <div v-if="showExamBankDialog" class="dialog-overlay" @click.self="showExamBankDialog = false">
      <div class="dialog-content"  @click.stop>
        <T_QA 
          :is-select-mode="true"
          @paper-selected="handlePaperSelected"
            class="custom-qa-style" 
        />
        <div class="dialog-actions">
          <div v-if="selectedPaper" class="selected-paper-info">
            已选问卷: {{ selectedPaper.paper_title }} (ID: {{ selectedPaper.survey_id }})
          </div>
          <button @click="showExamBankDialog = false" class="bac-button">取消</button>
          <button @click="confirmSelectPaper" class="confirm-button">确认选择</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getSurveyList, deleteSurvey, createNewSurveyAPI } from '@/services/api';
import PagiNation from '@/components/PagiNation.vue';
import T_QA from './T_QA.vue';
import { publishSurveyAPI } from '@/services/api';

export default {
  name: 'SurveyLibrary',
  components: {
    PagiNation,
    T_QA
  },
  props: {
    classId: {
      type: [String, Number],
      required: true,
    },
  },
  methods: {
  navigateToAnalysis(exam) {
    this.$router.push({
      name: 'SurveyAnalysis',
      params: {
        semesterId: this.classId,
        surveyId: exam.survey_id  // 确保参数名与路由配置完全一致
      }
    });
  }
},
  setup(props, { emit }) {
      const publishSurveyDialogVisible = ref(false);  // 控制模态框显示
    const endTime = ref("");  // 发布问卷的结束时间
    const selectedSemSurveyId = ref(null); 
    const showExamBankDialog = ref(false);
    const selectedPaper = ref(null);
    const currentTab = ref('全部问卷');
    const currentPage = ref(1);
    const itemsPerPage = 8;
    const tabs = ref([
      { label: '全部问卷', value: '全部问卷', count: null },
      { label: '未开始', value: 0, count: null },
      { label: '进行中', value: 1, count: null },
      { label: '已截止', value: 2, count: null },
    ]);
    const router = useRouter();

    const selectQuiz = (quiz) => {
      if (props.isSelectMode) {
        console.log('Selected quiz:', quiz);
        emit('paper-selected', quiz);
      }
    };
  // 打开发布模态框并传递选中的问卷ID
    const openPublishSurveyDialog = (semSurveyId) => {
      selectedSemSurveyId.value = semSurveyId;
      publishSurveyDialogVisible.value = true;
    };

    // 提交发布问卷
    const publishSurvey = async () => {
      if (!endTime.value || !selectedSemSurveyId.value) {
        ElMessage.warning("请填写完整的结束时间");
        return;
      }

      const data = {
        sem_survey_id: selectedSemSurveyId.value,
        end_time: endTime.value
      };

      try {
        const response = await publishSurveyAPI(data);
        if (response.data.status === 1) {
          ElMessage.success("问卷发布成功");
          publishSurveyDialogVisible.value = false;
          loadExams();  // 刷新问卷列表
        } else {
          ElMessage.error("发布失败: " + response.data.msg);
        }
      } catch (error) {
        ElMessage.error("发布失败: " + error.message);
      }
    };
    
    const handlePaperSelected = (paper) => {
      selectedPaper.value = paper;
      console.log('Selected survey ID:', paper?.survey_id);
    };

    const exams = ref([]);
    const selectedExams = ref(new Set());
    const isAnySelected = computed(() => selectedExams.value.size > 0);

    const allSelectedOnPage = computed(() => {
      return paginatedExams.value.every(exam => 
        selectedExams.value.has(exam.survey_id)
      );
    });

    const toggleSelectAll = () => {
      if (allSelectedOnPage.value) {
        paginatedExams.value.forEach(exam => {
          selectedExams.value.delete(exam.survey_id);
        });
      } else {
        paginatedExams.value.forEach(exam => {
          selectedExams.value.add(exam.survey_id);
        });
      }
    };

    // 加载问卷数据
    const loadExams = async () => {
      const semId = Number(props.classId);  // 确保 semId 是数字
      if (isNaN(semId)) {
        console.error('semId 无效:', props.classId);
        return;
      }

      try {
        const response = await getSurveyList(semId); // 传递 semId 和 status 1，表示获取已发布的问卷
        if (response.data.status === 1) {
          exams.value = response.data.data.map((exam) => ({
            ...exam,
            showActions: false,
            paper_id: exam.paper_id || null,
            survey_id: exam.survey_id || null,
          }));
          
          tabs.value.forEach((tab) => {
            if (tab.value === '全部问卷') {
              tab.count = exams.value.length;
            } else {
              tab.count = exams.value.filter((exam) => exam.status === tab.value).length;
            }
          });
        }
      } catch (error) {
        console.error('加载问卷失败:', error);
      }
    };

    const filteredExams = computed(() => {
      if (currentTab.value === '全部问卷') {
        return exams.value;
      } else {
        return exams.value.filter((exam) => exam.status === currentTab.value);
      }
    });

    const paginatedExams = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredExams.value.slice(start, end);
    });

    const totalPages = computed(() => {
      return Math.ceil(filteredExams.value.length / itemsPerPage);
    });

    const changeTab = (tabValue) => {
      currentTab.value = tabValue;
      currentPage.value = 1;
      selectedExams.value.clear();
    };

    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
      selectedExams.value.clear();
    };

    const statusLabel = (status) => {
      switch (status) {
        case 0:
          return '未开始';
        case 1:
          return '进行中';
        case 2:
          return '已截止';
        default:
          return '未知状态';
      }
    };

    const statusBadgeClass = (status) => {
      switch (status) {
        case 0:
          return 'badge-unstart';
        case 1:
          return 'badge-in-progress';
        case 2:
          return 'badge-closed';
        default:
          return 'badge-unknown';
      }
    };

   const navigateToNewExam = () => {
  newSurveyDialogVisible.value = true;
};

// 在setup()中添加状态和方法
const newSurveyDialogVisible = ref(false);
const newSurvey = ref({
  paper_title: '',
  paper_content: '',
  tech_id: Number(localStorage.getItem('id')),
  sem_id: Number(props.classId)
});

const createNewSurvey = async () => {
  try {
    const response = await createNewSurveyAPI(newSurvey.value);
    if (response.data.status === 1) {
      ElMessage.success('问卷创建成功');
      newSurveyDialogVisible.value = false;
      loadExams(); // 刷新问卷列表
    }
  } catch (error) {
    ElMessage.error('创建失败: ' + error.message);
  }
};


    const toggleSelection = (examId) => {
      if (selectedExams.value.has(examId)) {
        selectedExams.value.delete(examId);
      } else {
        selectedExams.value.add(examId);
      }
    };

    const batchDeleteExams = async () => {
      try {
        if (selectedExams.value.size === 0) {
          ElMessage.warning('请选择要删除的问卷！');
          return;
        }

        await ElMessageBox.confirm(
          `确定删除选中的 ${selectedExams.value.size} 个问卷吗？`,
          '警告',
          {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );

        const surveyIds = Array.from(selectedExams.value).join(',');
        const response = await deleteSurvey(surveyIds);

        if (response.data.status === 1) {
          ElMessage.success('删除成功！');
          selectedExams.value.clear();
          loadExams();
        } else {
          ElMessage.error('删除失败: ' + response.data.msg);
        }
      } catch (error) {
        // 用户取消操作自动捕获
      }
    };
    const deleteSingleSurvey = async (surveyId) => {
      try {
        await ElMessageBox.confirm('确定删除该问卷吗？', '警告', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
        });
        
        const response = await deleteSurvey(surveyId);
        if (response.data.status === 1) {
          ElMessage.success('删除成功！');
          loadExams();
        }
      } catch (error) {
        // 用户取消操作自动捕获
      }
    };
    const editSurvey = (paperId) => {
      router.push(`/edit-survey/${paperId}`);
    };
    const toggleNewExamMenu = () => {
      newExamMenuVisible.value = !newExamMenuVisible.value;
    };

    const selectExistingExam = () => {
      showExamBankDialog.value = true;
    };

    const newExamMenuVisible = ref(false);

    // 修改确认选择时的参数映射
  const confirmSelectPaper = async () => {
    console.log('创建问卷参数:', {
      sem_id: props.classId,
      survey_id: selectedPaper.value?.survey_id,  // 修改这里
      tech_id: localStorage.getItem('id')
    });
    
   try {
    if (!selectedPaper.value) {
      ElMessage.warning('请先选择问卷');
      return;
    }

    const response = await createNewSurveyAPI({
      sem_id: props.classId,
      tech_id: Number(localStorage.getItem('id')),
      survey_id: selectedPaper.value.survey_id  // 改为使用 survey_id 参数
    });

    if (response.data.status === 1) {
      ElMessage.success('问卷创建成功');
      loadExams();
      showExamBankDialog.value = false;
      selectedPaper.value = null;
    }
  } catch (error) {
    console.error('创建问卷失败:', error);
    ElMessage.error('问卷创建失败: ' + error.message);
  }
};
    onMounted(() => {
      loadExams();
    });

    return {
      editSurvey,
      currentTab,
      tabs,
      currentPage,
      totalPages,
      exams,
      filteredExams,
      paginatedExams,
      statusLabel,
      statusBadgeClass,
      changeTab,
      handlePageChange,
      navigateToNewExam,
      selectedExams,
      isAnySelected,
      toggleSelection,
      toggleSelectAll,
      allSelectedOnPage,
      batchDeleteExams,
      toggleNewExamMenu,
      newExamMenuVisible,
      selectExistingExam,
      showExamBankDialog,
      selectedPaper,
      confirmSelectPaper,
      T_QA,
      createNewSurveyAPI,
      selectQuiz,
      handlePaperSelected,
      newSurveyDialogVisible,
      newSurvey,
      createNewSurvey,
        publishSurveyDialogVisible,
      endTime,
      openPublishSurveyDialog,
      publishSurvey,
      deleteSingleSurvey
    };
  },
};
</script>



<style scoped>
.input-field {
  width: 95%;
  padding: 8px;
  margin: 10px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}
/* 新建问卷菜单 */
.new-question-button {
  background-color: #244382;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.new-question-menu {
    width: 74px;
    position: absolute;
    margin-top: -15px;
    right: 11.5vw;
    z-index: 10;
    background-color: white;
    border: 1px solid #ddd;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
    align-items: center;
}

.new-question-menu span {
  cursor: pointer;
  padding: 5px 0;
  color: gray;
  transition: color 0.3s;
}

.new-question-menu span:hover {
  color: #244382;
}
/* 与作业页面相似的样式 */
.filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter button {
  background: none;
  border: none;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  color: #333;
  transition: background-color 0.3s, color 0.3s;
}

.filter button.active {
  color: #244382;
  border-bottom: 2px solid #244382;
  font-weight: bold;
}

.filter .create-button {
  margin-left: auto;
  background-color: #244382;
  color: #fff;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.filter .create-button:hover {
  background-color: #376edc;
}

.exam-card {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
  transition: transform 0.3s;
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.exam-card:hover {
  transform: translateY(-5px);
  background-color: #f0f0f0;
}

.exam-checkbox {
  margin-right: 15px;
  margin-top: 5px;
  cursor: pointer;
  margin-top: 20px;
}

.exam-content {
  flex: 1;
}

.exam-header {
  display: flex;
  align-items: center;
  gap: 15px;
  position: relative;
}

.badge {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 14px;
}

.badge-unstart {
  background-color: #cae2f9;
  color: #519bd5;
}

.badge-in-progress {
  background-color: #d6ffdb;
  color: #3b995c;
}

.badge-closed {
  background-color: #f0f0f0cc;
  color: #666;
}

.exam-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
  position: absolute;
  right: 0;
  top: 0;
}

.edit-button,
.delete-button {
  background-color: transparent;
  border: none;
  cursor: pointer;
  color: #244382;
  font-size: 14px;
  transition: color 0.3s;
}

.edit-button:hover,
.delete-button:hover {
  color: #1e3661;
}

.floating-bar {
  width: 42.5%;
  text-align: right;
}

.floating-bar button {
  background-color: #244382;
  color: #fff;
  border: none;
  padding: 10px 15px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
}

.floating-bar button:hover {
  background-color: #376edc;
}
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.close-btn {
  cursor: pointer;
  font-size: 24px;
}

.dialog-actions {
  margin: 30px 0px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.selected-paper-info {
  font-size: 14px;
  color: #666;
  margin-right: auto;
  margin-left: 20px;
}
.custom-qa-style .btn.action-btn {
    background: #eee !important;  /* 默认灰色 */
    color: #666 !important;
    border: 1px solid #ddd !important;
}


.custom-qa-style .selected-btn {
      background: #4CAF50 !important;  /* 选中绿色 */
      color: white !important;
    }

.confirm-button {
  font-size: 15px;
  margin-right: 20px;
  background-color: #125AA2;
  color: #fff;
  padding: 10px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.confirm-button:hover {
  background-color: #3987d4;
}
.bac-button {
  font-size: 15px;
  background-color: #eee;
  color: rgb(80, 80, 80);
  border: rgb(95, 95, 95);
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.bac-button:hover{
  background-color:rgb(212, 212, 212) !important;
}
.dialog-content {
  justify-content: space-between;
  background: white;
  border-radius: 8px;
  width: 80%;
  max-width: 1200px;
  height: 80vh;
  padding: 20px;
  display: flex;
  flex-direction: column;
  /* 添加滚动条 */
  overflow-y: scroll; /* 外层容器隐藏滚动 */
}

.dialog-content::v-deep .exam-bank-container { /* 穿透样式到子组件 */
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}
</style>
